%include "pm.inc"
	org 07e00h
	jmp start
GDT: 	Descriptor 0,0,0
K_code: Descriptor 0,0ffffffffh,0c098h
K_date: Descriptor 0,0ffffffffh,0c092h
gdtlen	equ $-GDT
gdtptr	dw gdtlen-1
	dd 0
S_K_code equ K_code-GDT
S_K_date equ K_date-GDT
[BITS 16]
start:
	mov ax,cs
	mov ds,ax
	mov es,ax
	mov ss,ax
	mov sp,0100h
	
	xor eax,eax
	mov ax,ds
	shl eax,4
	add eax,GDT
	mov dword [gdtptr+2],eax
	lgdt [gdtptr]
	
	cli

	in al,92h
	or al,00000010b
	out 92h,al
	
	mov eax,cr0
	or eax,1
	mov cr0,eax
	
	jmp dword S_K_code:K_code_32
[BITS 32]


K_code_32:
	mov ax,S_K_date
	mov gs,ax
	mov ss,ax
	mov esp,0400000h
	mov edi,0b8000h
	mov ah,0ch
	mov al,'L'
	mov [gs:edi],ax
	mov edx,020100bh
	mov ebx,0200000h
	mov [gs:ebx],edx
	mov eax,0bh
	mov ebx,0201000h
	mov ecx,1024
page:
	mov [gs:ebx],eax
	add eax,1000h
	add ebx,4
	loop page
	mov edx,200h
	shl edx,12
	mov cr3,edx
	mov edx,cr0
	or edx,080000000h
	mov cr0,edx

	xor eax,eax
	mov eax,1
	push 0300000h
	push eax
	call S_K_code:hd_read
	jmp $
hd_read:
	mov dx,01f7h
ready:
	in al,dx
	and al,080h
	cmp al,080h
	jz ready

	mov al,2
	mov dx,01f2h
	out dx,al
	mov eax,[ss:esp+8]
	shl eax,1
	add eax,0e0000000h
	mov ecx,4
p:	
	inc dx
	out dx,al
	shr eax,8
	loop p

	mov al,020h
	inc dx
	out dx,al
check:
	in al,dx
	and al,088h
	cmp al,08h
	jnz check

	mov ebx,[ss:esp+12]
	mov ecx,512
	mov dx,01f0h
read:
	in ax,dx
	mov [gs:ebx],ax
	add bx,2
	loop read
	ret	
in_byte:
	mov dx,[ss:esp+8]
	in al,dx
	retf
out_byte:
	mov dx,[ss:esp+8]
	mov al,[ss:esp+10]
	out dx,al
	retf
